package com.lp.learn.learnspringboot.service.impl;

import com.lp.learn.learnspringboot.dao.UserMapper;
import com.lp.learn.learnspringboot.entity.User;
import com.lp.learn.learnspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Autowired
    @Qualifier("secondJdbcTemplate")
    private JdbcTemplate secondjdbcTemplate;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(int id) {
      List<User> users = jdbcTemplate.query("select id,name,age from user where id = ?",new Object[]{id},(ResultSet resultSet, int i)->getUser(resultSet));
      if(users != null && users.size()>0){
          return users.get(0);
      }
        return null;
    }

    @Override
    public List<User> getUsers() {
        String sql = "select id,name,age from user";
        List<User> users1 = jdbcTemplate.query(sql,(ResultSet resultSet, int i)-> getUser(resultSet));
        List<User> user2 = secondjdbcTemplate.query(sql,(ResultSet resultSet, int i)-> getUser(resultSet));
        List<User> users = new ArrayList<>();
        users.addAll(users1);
        users.addAll(user2);
        return users;
    }

    @Override
    public User findUserById(int id) {
        return userMapper.selectUserById(id);
    }

    private User getUser(ResultSet resultSet) throws SQLException {
        User u = new User();
        u.setId(resultSet.getInt("id"));
        u.setName(resultSet.getString("name"));
        u.setAge(resultSet.getInt("age"));
        return u;
    }
}
